from django import forms
from app01 import models
from django.db.models import Max
from django.utils import timezone
class StuModel_add_ModelForm(forms.ModelForm):
    classroom_name = forms.CharField(max_length=100, label="班级名称")
    class Meta:
        model = models.Student
        fields = ["username", "age", "gender", "birthday", "portrait_url",'password']

    def clean_classroom_name(self):
        classroom_name = self.cleaned_data.get('classroom_name')
        try:
            classroom = models.Classroom.objects.get(class_name=classroom_name)
        except models.Classroom.DoesNotExist:
            raise forms.ValidationError(f'班级 "{classroom_name}" 不存在，请检查输入。')
        return classroom

    def save(self, commit=True):
        student = super().save(commit=False)
        
        # 生成学号 student_id
        max_id = models.Student.objects.all().aggregate(Max('id'))['id__max']
        if max_id is None:
                max_id = 0
        next_id = max_id + 1
        current_year = timezone.now().year
        student.student_id = f"{current_year}0806{next_id}"
        
        # 添加班级关联
        student.classroom = self.cleaned_data['classroom_name']
        
        # 添加班主任或心理辅导员关联
        classroom = self.cleaned_data['classroom_name']
        if classroom.class_teacher:
            student.head_teacher = classroom.class_teacher
        
        if commit:
            student.save()
            
            # 更新班级的 student_count
            classroom.student_count = classroom.student_count + 1
            classroom.save()
        return student
class StuModel_list_all_ModelForm(forms.ModelForm):
    class Meta:
        model = models.Student
        fields = ["username","classroom","portrait_url","student_id","gender"]
class StuModel_list_ModelForm(forms.ModelForm):
    class Meta:
        model = models.Student
        fields = ["username", "age", "gender", 'student_id', 'classroom', "birthday","portrait_url","head_teacher","guardians"]
